package org.itboys.mobile.service.mysql.web.product;


import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.dto.lasted.SundayUploadDto;

import org.itboys.admin.entity.lasted.SystemDictionary;
import org.itboys.admin.service.SysDictionaryService;
import org.itboys.admin.service.lasted.SundayUploadService;
import org.itboys.admin.service.lasted.SystemDictionaryService;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.entity.mysql.product.SundayProduct;
import org.itboys.mobile.service.mongo.web.SundayPermissionService;

import org.itboys.mysql.service.BaseMySqlService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_商品_service_web
 * 当前为单规格。如果需要多规格，请自行扩展
 */
@Service
public class SundayProductService extends BaseMySqlService<SundayProduct> {

	@Autowired
	private SundayUploadService uploadService;
	@Autowired
	private SundayPermissionService permissionService;
	@Autowired
	private SystemDictionaryService dictionaryService;
	/**
	 * 分页查询商品
	 *
	 * @param request
	 * @return
	 */
	public PageResult<SundayProduct> selectProduct(HttpServletRequest request, List<Long> ids) {
		Map<String, Object> param = ParamUtil.packageMysqlPageParam(request, "name", "parentId", "categoryId", "isIndexRecommend","isIndexHot","isBrandRecommend","isBrandHot","isBrandGood","isGood");
		if (ListUtil.isNotNull(ids)) {
			param.put("ids", ids);
		}
		//2017年8月11日新增，如果传入了用户ID。则从权限中的获取对应的商品权限
		String memberId=request.getParameter("memberId");
		if(StringUtils.isNotEmpty(memberId)){
			List<Long> otherIds = permissionService.getPermission(Long.valueOf(memberId),1);
			if (ListUtil.isNull(otherIds)) {
				otherIds.add(0l);
			}
			param.put("ids", otherIds);
		}


		return new PageResult<SundayProduct>(super.select(param), super.count(param));
	}

	/**
	 * 新增/修改商品
	 * @param product
	 * @param imageFile
	 * @param rollImageFiles

	 * @throws IOException
	 */
	@Transactional
	public void save(
			SundayProduct product,
			MultipartFile imageFile,
			MultipartFile[] rollImageFiles,
			Long memberId
	) throws  Exception {
		//保存主图
		Map<String, String> map = uploadService.uploadSingle(imageFile);
		if(StringUtils.isNotEmpty(map.get(uploadService.UPLOAD_HALF_PATH))){
			product.setImage(map.get(uploadService.UPLOAD_HALF_PATH));
		}

		//编辑
		if(LongUtil.isNotZreo(product.getId())){
			//product.setUpdater(creator);
			//校验编号
			if(StringUtils.isNotEmpty(product.getNumber())){
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("id",product.getId());
				param.put("number_equal", product.getNumber());
				//param.put("type", Finals.TYPE_TIANJIE);
				//param.put("isDeletedNotEqual", Finals.YES);
				if(ListUtil.isNotNull(super.select(param))){
					throw new ErrorException("商品编号不能重复");
				}
			}
			super.update(product);
		}else{
			//校验编号
			Map<String, Object> param = new HashMap<String, Object>();
			if(StringUtils.isNotEmpty(product.getNumber())){
				param.put("number_equal", product.getNumber());
				if(ListUtil.isNotNull(super.select(param))){
					throw new ErrorException("商品编号不能重复");
				}
			}

			//product.setIsDeleted(Finals.NO);
			//product.setType(Finals.TYPE_TIANJIE);
			//product.setZoneId(zoneId);
			super.insert(product);
			//2017年8月13日，如果新增的是商户商品，需要添加对应的权限
			if(LongUtil.isNotZreo(memberId)){
				permissionService.savePermission(memberId,null,product.getId(),1,false);
			}
		}
		//保存轮播图
		List<Map<String, String>> maps = uploadService.
				uploadMultiWithRecord(rollImageFiles,product.getId(),SundayProduct.class.getSimpleName(),"商品ID"+product.getId()+",的轮播图");

	}
	/**
	 * 查询商品详情。后台
	 * @param productId
	 * @return
	 */
	public SundayProduct findOne(Long productId){
		SundayProduct product=null;
		if(LongUtil.isNotZreo(productId)){
			product = super.find(productId);
			//TianJieProduct
			//轮播图
			Map<String,Object> imgParam = new HashMap<String, Object>();
			imgParam.put("outClassName", product.getClass().getSimpleName().toString());
			imgParam.put("outClassId", productId);
			List<SundayUploadDto> rollImages = uploadService.selectNoPage(product.getId(),SundayProduct.class.getSimpleName());
			product.setRollImages(rollImages);

		}else{
			product=new SundayProduct();
		}

		return product;
	}
	//设置推荐。

	/**
	 * 设置为推荐
	 * @param productId
	 * @param status
	 * @param type 1，首页推荐。2其他待定
	 */

	/*public void setRecomment(Long productId,Integer status,Integer type){
=======
/*	public void setRecomment(Long productId,Integer status,Integer type){
>>>>>>> aa57f457b423e6acae91f63072378a342a355e47
			SundayProduct product = new SundayProduct();
			product.setId(productId);
			if(type==1){
				product.setIsIndexRecommend(status);
			}
			super.update(product);

	}*/

	/**
	 * 上下架
	 * @param id
	 * @param status
	 */
	public void change(Long id,Integer status){
		SundayProduct product = new SundayProduct();
		product.setId(id);
		product.setStatus(status);
		super.update(product);

	}

	/**
	 * 设置是否火爆，推荐，人气品牌相关内容
	 * @param id
	 * @param setType  是否设置或者取消
	 * @param type   设置的部位
	 */
	public void set(Long id,Integer setType,Integer type){
		SundayProduct product=super.find(id);
		Map<String,Object> param=new HashMap<String,Object>();
		Long count=0l;
		//设置部分
		if(setType==1){
			if(type==1){
				param.put("isIndexRecommend",1);
				count=super.count(param);
				if(count>=16){
					throw  new ErrorException("超过数量"+16);
				}
				product.setIsIndexRecommend(1);
			}else if(type==2){
				param.put("isIndexHot",1);
				count=super.count(param);
				if(count>=12){
					throw  new ErrorException("超过数量"+12);
				}
				product.setIsIndexHot(1);

			}else if(type==3){
				product.setIsBrandRecommend(1);
			}else if(type==4){
				product.setIsBrandHot(1);
			}else if(type==5){
				product.setIsBrandGood(1);
			}else if(type==6){
				product.setIsGood(1);
			}else if(type==7){
				product.setIsIndexText(1);
			}else if(type==8){
				product.setIsBrandJing(1);
			}else if(type==9){
				product.setIsBrandText(1);
			}
		}
		//取消设置
		if(setType==0){
			if(type==1){
				product.setIsIndexRecommend(0);
			}else if(type==2){
				product.setIsIndexHot(0);
			}else if(type==3){
				product.setIsBrandRecommend(0);
			}else if(type==4){
				product.setIsBrandHot(0);
			}else if(type==5){
				product.setIsBrandGood(0);
			}else if(type==6){
				product.setIsGood(0);
			}else if(type==7){
				product.setIsIndexText(0);
			}else if(type==8){
				product.setIsBrandJing(0);
			}else if(type==9){
				product.setIsBrandText(0);
			}
		}
		super.update(product);
	}
	/**
	 * 组装用户标签
	 */
	public SundayProduct packageTags(SundayProduct product,  boolean isAll){

		//组装项目招商模式标签
		List<SystemDictionary> joinModelDictionaries=dictionaryService.getDictionaryByKey("join_model");
		if(product.getJoinModel()==null)product.setJoinModel("");
		String [] joinModelTagIds = product.getJoinModel().split(",");

		List<Map<String,Object>> joinModelTags = new ArrayList<Map<String, Object>>();
		for(SystemDictionary dictionary:joinModelDictionaries){
			Map<String,Object> tag=new HashMap<String,Object>();
			tag.put("id",dictionary.getId());
			tag.put("name",dictionary.getValue());
			int isChecked=0;

			for(String modelTagId:joinModelTagIds){
				if(modelTagId.equalsIgnoreCase(String.valueOf(dictionary.getId()))){
					isChecked=1;
					break;
				}
			}
			tag.put("isChecked",isChecked);
			if(!isAll){
				if(isChecked==1)joinModelTags.add(tag);
			}else{
				joinModelTags.add(tag);
			}

		}
		product.setJoinModelTags(joinModelTags);

		//组装项目经营模式标签
		List<SystemDictionary> managerModelDictionaries=dictionaryService.getDictionaryByKey("manager_model");
		if(product.getManagerModel()==null)product.setManagerModel("");
		String [] managerModelTagIds = product.getManagerModel().split(",");

		List<Map<String,Object>> managerModelTags = new ArrayList<Map<String, Object>>();
		for(SystemDictionary dictionary:managerModelDictionaries){
			Map<String,Object> tag=new HashMap<String,Object>();
			tag.put("id",dictionary.getId());
			tag.put("name",dictionary.getValue());
			int isChecked=0;

			for(String managerTagId:managerModelTagIds){
				if(managerTagId.equalsIgnoreCase(String.valueOf(dictionary.getId()))){
					isChecked=1;
					break;
				}
			}
			tag.put("isChecked",isChecked);
			if(!isAll){
				if(isChecked==1)managerModelTags.add(tag);
			}else{
				managerModelTags.add(tag);
			}
		}
		product.setManagerModelTags(managerModelTags);


		//组装项目适合人群标签
		List<SystemDictionary> fitPersonDictionaries=dictionaryService.getDictionaryByKey("fit_person");
		if(product.getFitPerson()==null)product.setFitPerson("");
		String [] fitPersonTagIds = product.getFitPerson().split(",");

		List<Map<String,Object>> fitPersonTags = new ArrayList<Map<String, Object>>();
		for(SystemDictionary dictionary:fitPersonDictionaries){
			Map<String,Object> tag=new HashMap<String,Object>();
			tag.put("id",dictionary.getId());
			tag.put("name",dictionary.getValue());
			int isChecked=0;

			for(String fitPersonTagId:fitPersonTagIds){
				if(fitPersonTagId.equalsIgnoreCase(String.valueOf(dictionary.getId()))){
					isChecked=1;
					break;
				}
			}
			tag.put("isChecked",isChecked);
			if(!isAll){
				if(isChecked==1)managerModelTags.add(tag);
			}else{
				fitPersonTags.add(tag);
			}
		}
		product.setFitPersonTags(fitPersonTags);

		return product;
	}

	/**
	 * 审核
	 * @param id
	 */
	public void handle(Long id){
		SundayProduct product=super.find(id);
		//如果产品状态不为新生成的也不为修改的状态
		if(product.getStatus()!= SundayCommonConstants.product_status_dsh&&product.getStatus()!=SundayCommonConstants.product_status_new){
			throw  new ErrorException("请勿重复操作");
		}
		product.setStatus(SundayCommonConstants.user_status_ytg);
		super.update(product);
	}
}

